#include "iPlugingAssist.h"
char iPlugingAssist::m_DataFolder[256];

iPlugingAssist::iPlugingAssist(void)
{
	m_sTypeList = NULL;
	m_sKindList = NULL;
	m_sGroupList = NULL;
	m_sItemList = NULL;

	m_nTypeNum = 0;
	m_nKindNum = 0;
	m_nGroupNum = 0;
	m_nItemNum = 0;
}

iPlugingAssist::~iPlugingAssist(void)
{
	delete[] m_sTypeList;
	delete[] m_sKindList;
	delete[] m_sGroupList;
	delete[] m_sItemList;
}

iPlugingAssist* iPlugingAssist::Create( TCHAR* FileName )
{
	
	IPathConfigMgr* pMaxPath = IPathConfigMgr::GetPathConfigMgr();
	int pluginCount = 0;
	const TCHAR findFolder[] = "plugins\\";
	const TCHAR* sMaxPluginsDir;
	bool bFind = false;
	while ( true )
	{
		sMaxPluginsDir = pMaxPath->GetPlugInDir( pluginCount );
		if( !sMaxPluginsDir )
		{
			return NULL;
		}

		int length = strlen( sMaxPluginsDir );
		for ( int i = length, findCount = 8; i >= 0 && findCount >= 0 ; i--, findCount-- )
		{
			if( stricmp( &findFolder[findCount], &sMaxPluginsDir[i]) )
			{
				bFind =false;
				break;
			}
			bFind = true;
		}

		if ( bFind )
			break;

		++pluginCount;
	}	

	std::string sPlugIns = sMaxPluginsDir;
	sPlugIns += FileName;
	FILE* pStream = NULL;
	errno_t err = _tfopen_s( &pStream, sPlugIns.c_str(), _T("r") );
	if( err != 0 )
	{
		MessageBox( NULL, sPlugIns.c_str(), "can not file", MB_OK );
		return NULL;
	}

	char dataFolderName[64] = "\\datas";
	_fgetts( m_DataFolder, 256, pStream );
	int length = strlen( m_DataFolder )-1;
	if ( m_DataFolder[length] < 32 )
	{
		m_DataFolder[length] = 0;
	}
	strcat_s( m_DataFolder, 64, dataFolderName );

	iPlugingAssist* pAssist = new iPlugingAssist;	

	TCHAR pBuffer[256] = {0,};
	while ( !feof(pStream) )
	{
		_fgetts( pBuffer, 256, pStream );
		int nLength = strlen(pBuffer);
		if ( nLength > 0 )
			pBuffer[nLength-1] = 0;
		
		if ( !_tcsicmp(pBuffer, _T("[ModelType]")) )
		{
			pAssist->ReadDataList( pStream, pAssist->m_sTypeList, pAssist->m_nTypeNum );
		}
		else if ( !_tcscmp(pBuffer, _T("[ModelKind]") ) )
		{
			pAssist->ReadDataList( pStream, pAssist->m_sKindList, pAssist->m_nKindNum );
		}
		else if ( !_tcscmp(pBuffer, _T("[ModelGroup]") ) )
		{
			pAssist->ReadDataList( pStream, pAssist->m_sGroupList, pAssist->m_nGroupNum );
		}
		else if ( !_tcscmp(pBuffer, _T("[ItemType]") ) )
		{
			pAssist->ReadDataList( pStream, pAssist->m_sItemList, pAssist->m_nItemNum );
		}
	}
	fclose(pStream);
	return pAssist;
	
}
void iPlugingAssist::ReadDataList( FILE* pStream, std::string*& pString, unsigned int& nNum )
{
	char pBuffer[256] = {0,};
	_ftscanf_s( pStream, "%s", pBuffer, 256 );
	_ftscanf_s( pStream, "%d\n", &nNum );
	if( !nNum )
		return;

	pString = new std::string[nNum];
	for( unsigned int i = 0 ; i < nNum ; i++ )
	{
		if( feof( pStream ) )
			return;	
		_fgetts( pBuffer, 256, pStream );
		pString[i] = pBuffer;
	}
}